<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;


use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Crypt;
use Hash;
class UserController extends Controller
{
    //
    public function add()
    {
    	return view('admin.user.add', ['title' => '用户添加']);
    }

    public function insert(Request $request)
    {
    	$this -> validate($request,[
    			'name' => 'required|min:6|max:18',
    			'email' => 'required|email',
    			'password' => 'required',
    			'repassword' => 'required|same:password'
    		],[
    			'name.required' => '用户名不能为空',
    			'name.min' => '用户名最少为6位',
    			'name.max' => '用户名最多为18位',
    			'email.required' => '邮箱不能为空',
    			'email.email' => '邮箱格式不正确',
    			'password.required' => '确认密码不能为空',
    			'repassword.required' => '确认密码不能为空',
    			'repassword.same' => '确认密码不一致'
    		]);


    	// dd($request -> all());
    	$data = $request -> except('_token','repassword');

    	// //加密
    	// $data['password'] = Crypt::encrypt($data['password']);
    	// //解密
    	// $p = Crypt::decrypt($data['password']);
    	// dd($p);

//加密需要 use Hash;
    	//第二种加密
    	// $data['password'] = Hash::make($data['password']);
    	// dd($data['password']);

    	//第二种方法的验证密码正确的方法	第一个值是密码，第二个值得加密的密码
    	// $res = Hash::check('123123123','$2y$10$cYjeQfUhtvPxrPTG9iCwSOrnDzPFga.qavc4dW4nISVk0PMKmOSkW');
    	// dd($res);

    	$data['password'] = Crypt::encrypt($data['password']);
        //处理status字段
    	$data['status'] = 0;
    	
        //处理token字段     
        $data['remember_token'] = str_random(50);

        //处理时间
        $time = time();
        $data['created_at'] = $time;
        $data['updated_at'] = $time;


        //处理头像
    	if($request -> hasFile('pic'))
    	{
    		if($request -> file('pic') -> isValid())
    		{
    			$suffix = $request -> file('pic') -> getClientOriginalExtension();
    			$fileName = time().mt_rand(100000,999999).'.'.$suffix;
                //判断文件路径是否存在存在的的话就不用创建不存在的话就创建
                // if(!file_exists('./uploads/yhtx'))
                // {
                //     mkdir('./uploads/yhtx',true,'777');
                // }

                //移动文件
    			$move = $request -> file('pic') -> move('./uploads/yhtx',$fileName);
                    
            
                if($move)
                {
                    $data['pic'] = $fileName;
                }else{
                    $data['pic'] = 'default.jpg';
                }

       

    		}else{
                    $data['pic'] = 'default.jpg';
                }	
    	}else{
                    $data['pic'] = 'default.jpg';
                }



         $res = DB::table('users') -> insert($data);       
         if($res)
         {
            return redirect('/admin/user/index');
         }else{
            return back();
         }


    }

    //index
    public function index(Request $request)
    {

    // var_dump($request -> all()); 
        //查询10条数据
       // $data = DB::table('users') -> paginate($request -> input('num',10)); 

       // $data = DB::table('users') -> where('name','like', '%'.$request -> input('keywords').'%') -> paginate($request -> input('num',10)); 


    // 高级where
    $data = DB::table('users') -> where(function($query) use ($request){
        $query -> where('name','like','%'.$request -> input('keywords').'%');
    }) -> paginate($request -> input('num',10));


       return view('admin.user.index',['data' => $data,'request' => $request -> all()]);
    }

    public function ajaxStatus(Request $request)
    {
        $id = $request -> input('id');

        //查询
        $status =  DB::table('users') -> where('id',$id) -> first() -> status;
           

    //判断
    //判断
     if($status == 0)
        {
            $res = DB::table('users') -> where('id',$id) -> update(['status' => 1]);

            if($res)
            {
                return  1;
            }else{
                return 2;
            }

        }elseif($status == 1)
        {
            $res = DB::table('users') -> where('id',$id) ->update(['status' => 0]);

            if($res)
            {
                return 0;

            }else{
                return 2;
            }
        } 
 }

  
        public function ajaxName(Request $request)
        {
            $id = $request -> id;
            $name = $request -> name;

            $data = DB::table('users') -> where('name',$name) ->first();

            if($data)
            {
                return 4;

            }else
            {
               $res =  DB::table('users') -> where('id',$id) -> update(['name' => $name] );

             if($res)
             {
                return 1;
             }else{
                return 0;
             }
           
            }

        }

        //edit
        public function edit($id)
        {
            $data = DB::table('users') -> where('id',$id) -> first();

            return view('admin.user/edit',['data' => $data,'title' => '用户编辑']);
        }

        //update
        public function update(Request $request)
        {
            $data = $request -> except('_token','id');
            // dd($data);   
            //获取原来的图片
            $oldPic =DB::table('users') -> where('id',$request -> id) -> first() -> pic;

            if($request -> hasFile('pic'))
            {
                 if($request -> file('pic') -> isValid())
                 {
                    $suffix = $request -> file('pic') -> getClientOriginalExtension();
                    $fileName = time().mt_rand(100000,999999).'.'.$suffix;
                    
                    //移动文件
                    $move = $request -> file('pic') -> move('./uploads/yhtx',$fileName);

                  if($move)     
                    {                   
                        $data['pic'] = $fileName;
                        //删除原来的图片
                        unlink('./uploads/yhtx/'.$oldPic);
                    }   
            }
}
           
            $res = DB::table('users') -> where('id',$request -> id) -> update($data);


                 if($res)
                 {
                    return redirect('/admin/user/index') -> with(['info'=> '修改成功']);
                 }else{
                    return back() -> with(['info'=> '修改失败']);
                 }

            }
            //删除
            public function delete($id)
            {
                $res = DB::table('users') -> delete($id);
                //获取原来的图片
                 $oldPic =DB::table('users') -> where('id',$request -> id) -> first() -> pic;

                if($res)
                 {
                    //删除图片
                    if(file_exists('./uploads/yhtx/'.$oldPic))
                    {
                        unlink('./uploads/yhtx/'.$oldPic);
                    }
                    return redirect('/admin/user/index') -> with(['info'=> '删除成功']);
                 }else{
                    return back() -> with(['info'=> '删除失败']);
                 }


            }





        }